package org.example.aop;

import org.example.dao.UserDao;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import org.springframework.web.WebApplicationInitializer;

import java.lang.reflect.Method;

/**
 * Company 源辰信息
 *
 * @author navy
 * @date 2024/4/20
 * Email haijunzhou@hnit.edu.cn
 */
// 基于继承的代理
public class CGLIBProxy {

    static Object proxy(Object target){
        Enhancer enhancer = new Enhancer();
        // 设置父类, 被代理对象的类
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(
                    Object proxy,
                    Method method,
                    Object[] args,
                    MethodProxy methodProxy) throws Throwable {
                System.out.println("==================== 前置拦截");
                Object res = methodProxy.invoke(target, args);
                System.out.println("==================== 后置拦截");
                return res;
            }
        });
        WebApplicationInitializer a;
        // 生成代理对象
        return enhancer.create();
    }

    public static void main(String[] args) {
        A b = new B();
        A proxy = (A) proxy(b);
        proxy.test();

        UserDao userDao = new UserDao();
        UserDao userDao1 = (UserDao) proxy(userDao);
        userDao1.deleteById(100);

    }
}
